package com.letv.business.flow.album;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.letv.adlib.managers.status.video.IVideoStatusInformer;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.business.flow.album.model.AlbumStreamSupporter;
import com.letv.business.flow.album.model.AlbumUrl;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.AlbumPayInfoBean;
import com.letv.core.bean.DDUrlsResultBean;
import com.letv.core.bean.DownloadDBListBean;
import com.letv.core.bean.DownloadDBListBean.DownloadDBBean;
import com.letv.core.bean.HomeMetaData;
import com.letv.core.bean.PlayRecord;
import com.letv.core.bean.VideoBean;
import com.letv.core.bean.VideoFileBean;
import com.letv.core.bean.VideoListBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LetvLogApiTool;
import com.letv.core.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 点播流程基类
 * 
 * @author zhuqiao
 *
 */
public abstract class AlbumPlayBaseFlow {
    protected Context mContext;
    protected Handler mHandler = new Handler();

    protected int mLaunchMode;
    protected int mActivityLaunchMode;
    /** 视频id **/
    protected long mVid = 0;
    /** 专辑id **/
    protected long mAid = 0;// 如果是专题，那么代表pid
    /** 频道id **/
    protected long mCid = 0;
    /** 专题id **/
    protected long mZid = 0;

    /** zhuqiao测试，从其启动流程到得到真实地址所消耗时间 **/
    public static long sRequestRealUrlConsumetime = 0;
    /** zhuqiao测试，广告消耗时间 **/
    public static long sRequestAdsConsumetime = 0;
    /** zhuqiao测试，从设置真实地址到播放出来所消耗时间 **/
    public static long sToPlayConsumetime = 0;
    /** zhuqiao测试，获取播放记录所消耗时间 **/
    public static long sRequestRecodeConsumetime = 0;
    /** zhuqiao测试，获取本地视频所消耗时间 **/
    public static long sRequestLocalConsumetime = 0;

    /** 码流支持信息 **/
    protected final AlbumStreamSupporter mStreamSupporter = new AlbumStreamSupporter();

    /** 点播流程中的各种url **/
    protected final AlbumUrl mAlbumUrl = new AlbumUrl();

    /** 点播流程中涉及到的信息 **/
    protected AlbumPlayInfo mPlayInfo = new AlbumPlayInfo();

    private Bundle mBundle;

    /** 请求专辑收费详情 **/
    protected AlbumPayInfoBean mPayInfo;
    protected VideoFileBean mVideoFile;

    /** 是否已经初始化 **/
    protected boolean mHasInited;

    /** 是否降码流 **/
    protected boolean mShouldDeclineStream;

    /** 当前视频所在专辑（可能为空） **/
    protected AlbumNew mVideoBelongedAlbum;

    /** 是否是下载状态 **/
    public boolean mIsDownloadState;

    protected int mDownloadStreamLevel = 0;

    /** 播放视频的播放记录 **/
    protected PlayRecord mPlayRecord;

    /** 视频列表当前页页码 **/
    protected int mCurPage = 1;

    /** 是否是杜比 **/
    protected boolean mIsDolby;

    /** 跳过时间 **/
    protected long mSeek;
    /** 本地视频(不包括有下载记录的视频)播放的位置，需要传给小窗,单位s **/
    protected long mLocalSeek;

    /** 是否是切换码流播放 **/
    protected boolean mIsChangeStream;

    /** 本地视频列表 **/
    protected DownloadDBListBean mDownloadDBListBean;

    /** 播放来源 **/
    protected int mFrom;
    /** 是否返回原应用 **/
    protected boolean mBackToOriginalApp;

    /** 当前播放的下载文件是否是高清 **/
    protected boolean mCurrDownloadFileIsHd = false;
    protected DownloadDBBean mDownloadDBBean;

    /** 播放推荐的连播数据 **/
    protected ArrayList<HomeMetaData> mVideoRecommendList;
    /** 推荐的连播数据的当前位置 **/
    protected int mVideoRecommendIndex = 0;
    /** 即将播放的推荐视频信息 **/
    protected HomeMetaData mVideoRecommend;

    /**
     * 视频集合，以页数为key,主要用于文件夹格式，页数和视频列表结合的 map映射
     */
    @SuppressLint("UseSparseArrays")
    public final HashMap<Integer, VideoListBean> mVideos = new HashMap<Integer, VideoListBean>();

    /** v5.4.1 口袋看球（判断从下载->口袋看球进来） **/
    // protected boolean mIsFromWorldCapDownload;

    /** 是否使用p2p播放 **/
    protected boolean mIsP2pMode = false;

    /** 本地视频地址(不包括有下载记录的视频) **/
    protected String mLocalPath;

    /**
     * 播放是否是高清 1：极速，2：流畅，3：高清， 4：超清
     */
    protected int mPlayLevel; // add libo 与卡顿有关

    /** 当前正在播放的视频对象 **/
    protected VideoBean mCurrentPlayingVideo;
    /**
     * 保存第一次播放的视频信息（不能为空）
     * 主要是为了相关里面联播时数据不能变
     */
    protected VideoBean mFirstVideo;

    /** 当前选择的码流 **/
    protected int mSelectStream = -1;

    /** 添加硬解m3u8 **/
    protected boolean mHardDecode = false;

    /** 当前播放视频的码流 **/
    protected String mStreamLevel;

    /** 是否可以跳小窗播放 **/
    protected boolean mCanToPip = false;

    /** 调度地址 **/
    protected DDUrlsResultBean mDdUrlsResult;

    /** 是否是联通3G用户.联通流量3g套餐播放不需要提示3g **/
    protected boolean mIsWo3GUser = false;
    /** 是否播放的是免流量地址 **/
    protected boolean mIsPlayFreeUrl = false;
    /** 是否sdk初始化失败 **/
    protected boolean mIsSdkInitFail = false;

    /** 标记是否是本地下载文件 **/
    protected boolean mIsDownloadFile = false;

    /** 是否第一次播放 **/
    protected boolean mIsFirstPlay;

    /** 是否跳过片头片尾 **/
    protected boolean mIsSkip;

    /** 下载是否是高清 **/
    protected boolean mDownloadHd;

    /** 网络状态 **/
    protected int mOldNetState = -1;

    /** 是否销毁了播放器第一次播放 **/
    protected boolean mIsLaunchPlay = true;

    /** 可用的码流列表 **/
    protected final List<Integer> mLevelList = new ArrayList<Integer>();

    /** cde状态码 **/
    protected int mCdeStatusCode = -1;

    /** 本地文件地址 **/
    protected String mFilePath;

    /** 是否播放广告 **/
    protected boolean mNeedPlayAd = true;
    /** 暂停广告标志 **/
    protected boolean mIsPauseAdIsShow = false;

    /** 第一次请求广告的时间 **/
    protected long mFirstRequest = 0;
    /** 用于控制两次广告请求之间的间隔单位毫秒 **/
    protected long mRequestStep = 500;

    /**
     * 记录到播放流程，哪一个环节失败了；<br>
     * 0 无失败 ，1 专辑详情，2，视频详情，3，视频列表，4，canplay和付费信息接口，5，videofile接口，6，调度中，7，缓冲中或播放中
     */
    protected int mPlayCallBackState;

    protected boolean mIsScanVideo;

    /** 跳过片尾提示一次 **/
    public boolean mIsShowSkipEnd = true;

    protected boolean mIsInitReport = false;
    protected boolean mIsStartPlayLocalDownloadEnter = false;

    /** 广告是否播放完成 **/
    protected boolean mIsAdFinished;
    /** 是否准备播放广告 **/
    protected boolean mAlreadyPlayAd = false;
    /** 是否有广告 **/
    protected boolean mHasAd = false;
    /** 广告数量. **/
    protected int mAdCount = 0;

    protected boolean mIsStarted;

    /** 切换码流时的seek **/
    protected int mChangeStreamSeek = -1;

    /** 是否点击了跳过广告 **/
    protected boolean mIsClickShipAd = false;

    /**
     * 新增IVideoStatusInformer ，用于客户端将播放状态通知给广告
     */
    public IVideoStatusInformer mIVideoStatusInformer;
    protected  String streamType;

    public AlbumPlayBaseFlow(Context context, int launchMode, Bundle bundle) {
        mContext = context.getApplicationContext();
        mLaunchMode = launchMode;
        mBundle = bundle;
        initDataFromIntent(bundle);
        initDataWithLaunchMode(bundle);
    }

    public abstract void start();

    /**
     * 从intent从获取数据
     */
    protected void initDataFromIntent(Bundle bundle) {
        mFrom = bundle.getInt(PlayConstant.FROM, PlayConstant.LAUNCH_FROM_CHANNEL);
        mBackToOriginalApp = bundle.getBoolean(PlayConstant.BACK);
        mActivityLaunchMode = bundle.getInt(PlayConstant.LAUNCH_MODE, PlayConstant.LAUNCH_MODE_ALBUM);

        if (mFrom == PlayConstant.LAUNCH_FROM_RECOMMEND) {
            initDataWhenFromRecommend(bundle);
        } else if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE) {
            mPlayInfo.hTime = bundle.getLong(PlayConstant.HTIME, 0);
        } else if (mFrom == PlayConstant.LAUNCH_FROM_DOWNLOAD_WORLDCUP) {
            // mIsFromWorldCapDownload = true;
        }
    }

    /**
     * 当来自推荐时，初始化数据
     */
    @SuppressWarnings("unchecked")
    private void initDataWhenFromRecommend(Bundle bundle) {
        if (bundle.getSerializable(PlayConstant.VIDEO_LIST) != null) {
            mVideoRecommendList = (ArrayList<HomeMetaData>) bundle.getSerializable(PlayConstant.VIDEO_LIST);
        }
        mVideoRecommendIndex = bundle.getInt(PlayConstant.RECOMMEND_INDEX, mVideoRecommendIndex) + 1;
        if (mVideoRecommendList != null) {
            mVideoRecommend = BaseTypeUtils.getElementFromList(mVideoRecommendList, mVideoRecommendIndex);
        }
    }

    /**
     * 根据launchMode初始化数据
     */
    protected void initDataWithLaunchMode(Bundle bundle) {
        if (mLaunchMode == PlayConstant.PLAY_ALBUM || mLaunchMode == PlayConstant.PLAY_DOWNLOAD) {
            mAid = Math.max(0, bundle.getInt(PlayConstant.AID));
            mVid = Math.max(0, bundle.getInt(PlayConstant.VID));
            mIsDolby = bundle.getBoolean(PlayConstant.IS_DOLBY);
        } else if (mLaunchMode == PlayConstant.PLAY_VIDEO) {
            mVid = Math.max(0, bundle.getInt(PlayConstant.VID));
            mIsDolby = bundle.getBoolean(PlayConstant.IS_DOLBY);
            // 添加对leso的判断
            if (mIsDolby || mFrom == PlayConstant.LAUNCH_FROM_MSITE) {
                mAid = bundle.getInt(PlayConstant.AID, 0);
            }
        } else {
            // 获取SD卡文件的路径
            mAlbumUrl.realUrl = bundle.getString(PlayConstant.URI);
            // zhuqiao dlna
            // dlna.playUrl = realUrl;
        }
        mSeek = bundle.getLong(PlayConstant.SEEK);
    }

    public void addPlayInfo(String key, String value) {
        LetvLogApiTool.getInstance().saveExceptionInfo(
                "专辑Current Time :" + StringUtils.getTimeStamp() + "  " + key + " : " + value + "  ");
    }

    // ------------------------------ get set ------------------------------
    public int getLaunchMode() {
        return mLaunchMode;
    }

    public void setmLaunchMode(int mLaunchMode) {
        this.mLaunchMode = mLaunchMode;
    }

    public  int getActivityLaunchMode(){return  mActivityLaunchMode;}

    public String getStreamType(){return  streamType;}

    public long getVid() {
        return mVid;
    }

    public void setVid(long vid){mVid = vid;}

    public VideoFileBean getmVideoFile(){
        return mVideoFile;
    }

    public void setmVideoFile(VideoFileBean mVideoFile){
        this.mVideoFile = mVideoFile;
    }

    public long getAid() {
        return mAid;
    }
    public void setAid(long aid){mAid = aid;}

    public long getCid() {
        return mCid;
    }

    public void setCid(long cid){mCid = cid;}

    public long getZid() {
        return mZid;
    }

    public int getFrom() {
        return mFrom;
    }

    public Bundle getBundle() {
        return mBundle;
    }

    public AlbumUrl getAlbumUrl() {
        return mAlbumUrl;
    }

    public  Context  getContext(){return mContext;}

    /**
     * 获取当前播放的视频
     * 
     * @return
     */
    public VideoBean getPlayingVideo() {
        return mCurrentPlayingVideo;
    }

    public boolean isDolby() {
        return mIsDolby;
    }

    public void setDobly(boolean isDolby){mIsDolby = isDolby;}

    public boolean isDownloadFile() {
        return mIsDownloadFile;
    }

    public boolean isFirstPlay() {
        return mIsFirstPlay;
    }

    public void setFirstPlay(boolean firstPlay) {
        mIsFirstPlay = firstPlay;
    }

    public boolean isSkip() {
        return mIsSkip;
    }

    public boolean setSkip(boolean isSkip) {
        mIsSkip = isSkip;
        return mIsSkip;
    }

    public AlbumStreamSupporter getStreamSupporter() {
        return mStreamSupporter;
    }

    public int getPlayLevel() {
        return mPlayLevel;
    }

    public void setPlayLevel(int playLevel) {
        mPlayLevel = playLevel;
    }

    public List<Integer> getLevelList() {
        return mLevelList;
    }

    public int getSelectStream() {
        return mSelectStream;
    }

    public void setSelectStream(int selectStream) {
        mSelectStream = selectStream;
    }

    public boolean shouldDeclineStream() {
        return mShouldDeclineStream;
    }

    public String getFilePath() {
        return mFilePath;
    }

    public int getPlayCallBackState() {
        return mPlayCallBackState;
    }

    public void setPlayCallBackState(int state) {
        mPlayCallBackState = state;
    }

    public boolean isScanVideo() {
        return mIsScanVideo;
    }

    public void setScanVideo(boolean scanVideo) {mIsScanVideo = scanVideo;}

    public boolean isAdFinished() {
        return mIsAdFinished;
    }

    public void setAdFinished(boolean finish) {
        mIsAdFinished = finish;
    }

    public boolean isCurrDownloadFileIsHd() {
        return mCurrDownloadFileIsHd;
    }

    public boolean isAlreadyPlayAd() {
        return mAlreadyPlayAd;
    }

    public void setAlreadyPlayAd(boolean alreadyPlayAd) {
        mAlreadyPlayAd = alreadyPlayAd;
    }

    public boolean isHasAd() {
        return mHasAd;
    }

    public void setHasAd(boolean hasAd) {
        mHasAd = hasAd;
    }

    public int getAdCount() {
        return mAdCount;
    }

    public void setAdCount(int adCount) {
        mAdCount = adCount;
    }

    public PlayRecord getPlayRecord() {
        return mPlayRecord;
    }

    public void setPlayRecord(PlayRecord playRecord){mPlayRecord = playRecord;}

    public boolean isBackToOriginalApp() {
        return mBackToOriginalApp;
    }

    public void setCdeStatusCode(int code) {
        mCdeStatusCode = code;
    }

    public int getCdeStatusCode(){return mCdeStatusCode;}

    public AlbumPayInfoBean getPayInfo() {
        return mPayInfo;
    }

    public  void setPayInfo(AlbumPayInfoBean payInfo){mPayInfo = payInfo;}

    public boolean isP2pMode() {
        return mIsP2pMode;
    }

    public void setIsP2pMode(boolean isP2pMode) {mIsP2pMode = isP2pMode;}

    public String getStreamLevel() {
        return mStreamLevel;
    }

    public void setStreamLevel(String streamLevel){mStreamLevel = streamLevel;}

    public boolean isWo3GUser() {
        return mIsWo3GUser;
    }

    public void setCanToPip(boolean canToPip) {
        mCanToPip = canToPip;
    }

    public boolean isPauseAdIsShow() {
        return mIsPauseAdIsShow;
    }

    public void setIsPauseAdIsShow(boolean isPauseAdIsShow) {
        mIsPauseAdIsShow = isPauseAdIsShow;
    }

    /**
     * 获取当前播放的视频所在的专辑
     * 
     * @return
     */
    public AlbumNew getAlbum() {
        return mVideoBelongedAlbum;
    }

    public void setAlbum(AlbumNew album) {
        mVideoBelongedAlbum = album;
    }

    public long getSeek() {
        return mSeek;
    }

    public long getLocalSeek() {
        return mLocalSeek;
    }

    public void setLocalSeek(long localSeek) {
        mLocalSeek = localSeek;
    }

    public int getCurrentPage() {
        return mCurPage;
    }

    public long getLastVideoPos() {
        if (null == mVideos || mVideos.size() == 0) {
            return -1;
        }

        Set<Integer> set = mVideos.keySet();
        int maxPage = -1;
        for (Integer page : set) {
            maxPage = Math.max(maxPage, page);
        }

        VideoListBean listBean = mVideos.get(maxPage);
        return listBean.get(listBean.size() - 1).getId();
    }

    public VideoBean getFirstVideo() {
        return mFirstVideo;
    }

    public boolean hasInited() {
        return mHasInited;
    }

    public void setHasInited(boolean hasInited) {
        mHasInited = hasInited;
    }

    public AlbumPlayInfo getPlayInfo() {
        return mPlayInfo;
    }

    public  void setPlayInfo(AlbumPlayInfo playInfo){mPlayInfo = playInfo;}

    public boolean isClickShipAd() {
        return mIsClickShipAd;
    }

    public void setIsClickShipAd(boolean isClickShipAd) {
        mIsClickShipAd = isClickShipAd;
    }

    public void setVideoRecommendList(ArrayList<HomeMetaData> list) {
        mVideoRecommendList = list;
    }

    public void setVideoRecommendIndex(int index) {
        mVideoRecommendIndex = index;
    }

    public void setVideoRecommend(HomeMetaData videoRecommend) {
        mVideoRecommend = videoRecommend;
    }

    public HomeMetaData getVideoRecommend() {
        return mVideoRecommend;
    }

    public  DDUrlsResultBean getDdUrlsResult(){return  mDdUrlsResult;}

    public  void  setDdUrlsResult(DDUrlsResultBean DdUrlsResult){
        mDdUrlsResult = DdUrlsResult;
    }

    /**
     * 是否是本地视频(下载、扫描、sd卡中的视频F)
     * 
     * @return
     */
    public boolean isLocalFile() {
        return mIsDownloadFile || (!TextUtils.isEmpty(mAlbumUrl.realUrl) && !mAlbumUrl.realUrl.startsWith("http"));
    }
}
